import java.awt.BorderLayout;
import java.awt.event.ActionEvent;  
import java.awt.event.ActionListener;  
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;  
import java.awt.event.MouseListener;  
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import javax.swing.JFrame;  
import javax.swing.JMenuItem;  
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;  
import javax.swing.JScrollPane;  
import javax.swing.JTree;  
import javax.swing.tree.DefaultMutableTreeNode;  
import javax.swing.tree.DefaultTreeCellEditor;  
import javax.swing.tree.DefaultTreeCellRenderer;  
import javax.swing.tree.DefaultTreeModel;  
import javax.swing.tree.TreePath;  
import javax.swing.tree.TreeSelectionModel;  

import org.w3c.dom.Element;
import org.w3c.dom.Text;

/**
 * Title:  Tree.java
 * Description:  create tree for navigation window and manipulating files
 * Copyright:    Copyright (c) 2010
 * @author WANG Jiechao
 * @version 1.0
 * if you have any problem about XML DOM, consult The Java Tutorial
 */

public class Tree extends JFrame implements MouseListener,ActionListener {  

    private static final long serialVersionUID = 1L;  
    final JTree tree;  
    JPopupMenu newProject,popMenu;
    JMenuItem projectItem,addItem,delItem,editItem;
    JPanel treePanel;
    JClosableTabbedPane text1 = null;
    String selName;
    Boolean newfile;
    getXML getXml=new getXML();


    public Tree() {  
    	DefaultMutableTreeNode top=new DefaultMutableTreeNode("The navigation window");
    	getXml.createNodes(top);
        tree = new JTree(top);  
        tree.setEditable(true);  
        tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);  
        tree.addMouseListener(this); 
        tree.addMouseListener(ml);
        tree.setCellEditor(new DefaultTreeCellEditor(tree, new DefaultTreeCellRenderer())); 
        
        getContentPane().add(tree);  
        setSize(200, 200);  
  
        popMenu = new JPopupMenu();  
        addItem = new JMenuItem("Add");  
        addItem.addActionListener(this);  
        delItem = new JMenuItem("Delete");  
        delItem.addActionListener(this);  
        editItem = new JMenuItem("Rename");  
        editItem.addActionListener(this);  
  
        popMenu.add(addItem);  
        popMenu.add(delItem);  
        popMenu.add(editItem);  
        
        newProject = new JPopupMenu();  
        projectItem = new JMenuItem("New Project");  
        projectItem.addActionListener(this);  
        
        newProject.add(projectItem);  
              
        tree.setComponentPopupMenu(newProject);
        
        treePanel = new JPanel();
        treePanel.setLayout(new BorderLayout());
        treePanel.add(new JScrollPane(tree),BorderLayout.CENTER);
        //treePanel.setSize(2500,2500);
        getContentPane().add(treePanel);  
    }  
    
    MouseListener ml = new MouseAdapter() {
        public void mousePressed(MouseEvent e) {
            int selRow = tree.getRowForLocation(e.getX(), e.getY());
            //TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
        	DefaultMutableTreeNode selected = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); 
        	selName = (String)selected.getUserObject();
            if(selRow != -1) {
                if(e.getClickCount() == 1) {                   
                }
                else if(e.getClickCount() == 2&&selected.isLeaf()) {
                	System.out.printf(selName + " has been clicked twice\n");                    
					try {
						Group.openFile();
					} catch (IOException e1) {						
						e1.printStackTrace();
					}
                }
            }
        }
        //} 
    };

    


    public void mouseClicked(MouseEvent e) {
    	if (e.getSource() == projectItem){
    		System.out.print("1");
    	}
  
    }  
  
    public void mouseEntered(MouseEvent e) {  
  
    }  
  
    public void mouseExited(MouseEvent e) {  
  
    }  
  
    public void mousePressed(MouseEvent e) {  
        TreePath path = tree.getPathForLocation(e.getX(), e.getY()); 
        if (path == null) {  
            return;  
        }  
        tree.setSelectionPath(path);  
  
        if (e.getButton() == 3) {  
            popMenu.show(tree, e.getX(), e.getY());  
        }  
    }  
  
    public void mouseReleased(MouseEvent e) {  
  
    }  
  
    public void actionPerformed(ActionEvent e) {  
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();  
        if (e.getSource() == addItem) {
        	Group.goTo(treePanel, "Please enter the name of the new node", "New node", "No name no creation!", "ERROR");
            ((DefaultTreeModel) tree.getModel()).insertNodeInto(new DefaultMutableTreeNode(Group.s), node, node  
                    .getChildCount());  
            tree.expandPath(tree.getSelectionPath());  
/*            Text nameText = getXml.getdoc().createTextNode("zs");
            Element name = getXml.getdoc().createElement("name");
            name.appendChild(nameText);
            getXml.getdoc().appendChild(name);*/
            CreateXML.doc2XmlFile(getXml.getdoc(), getXml.getXMLFileName());
        } else if (e.getSource() == delItem) { 
           
            if (node.isRoot()) {
            	JOptionPane.showMessageDialog(this,
            		    "You cannot delete root node",
            		    "ERROR",
            		    JOptionPane.ERROR_MESSAGE);
                return;  
            }
            if (node.isLeaf()){
            	int n = JOptionPane.showConfirmDialog(this,
            	    "Are you sure to delete this file?\n" +
            	    "( the deletion of this file will not affect the file on your disk )",
            	    "Warning",
            	    JOptionPane.WARNING_MESSAGE);
            	if(n==JOptionPane.YES_OPTION)
            		((DefaultTreeModel) tree.getModel()).removeNodeFromParent(node); 
            }
            else{
            	int n = JOptionPane.showConfirmDialog(this,
            		"Are you sure to delete this project?\n" +
                	"( the deletion of this project will not affect the files on your disk )",
                	"Warning",
                	JOptionPane.WARNING_MESSAGE);  
            	if(n==JOptionPane.YES_OPTION)
            		((DefaultTreeModel) tree.getModel()).removeNodeFromParent(node); 
            }
        } else if (e.getSource() == editItem) {  
            tree.startEditingAtPath(tree.getSelectionPath());  
        }  
    }  
    
    public JPanel getTreePanel(){
    	return treePanel;
    }
    /**
     * This method is used to open the file corresponding to the node double selected
     * @throws IOException 
     */
    public void openFile(JClosableTabbedPane text1) throws IOException{
        try { //use a buffer reader to read in the file selected
    	
    		this.text1=text1;
    		
            String fileName = selName+".txt";
            System.out.print(fileName);
            FileReader filereader = new FileReader(fileName); // use a filereader to read the file  
            
    		Panel2A file = new Panel2A();
    		text1.addTab(selName+" ", file);

    		String templine; // a string to read a line of the file 
    		String all; // a string to record all the content of the file
    		
            BufferedReader bffreader = new BufferedReader(filereader);

            all = ""; // initialize the string to be blank

            while ((templine = bffreader.readLine()) != null) { // if there is a line, read the line in the templine

                all = all + templine + '\n'; // all is the original"all" plus new templine plus an "enter"

            }
            System.out.print(all);
            file.setText(all);

            filereader.close();
            newfile = false;

        } catch (FileNotFoundException e1){ System.out.print("************");
        JOptionPane.showMessageDialog(text1,
        	    "file not found!!",
        	    "ERROR",
        	    JOptionPane.ERROR_MESSAGE);

        }    
    }
  
    public static void main(String[] args) {  
        Tree frame = new Tree();  
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
        frame.setVisible(true);  
    }  
}  